package com.godofball.todo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.godofball.todo.entity.utils.AppHttpCodeEnum;
import com.godofball.todo.entity.utils.ResponseResult;
import com.godofball.todo.mapper.UserMapper;
import com.godofball.todo.entity.User;
import com.godofball.todo.service.UserService;
import com.godofball.todo.utils.JwtHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;

/**
 * ç”¨æˆ·è¡¨(User)表服务实现类
 *
 * @author makejava
 * @since 2024-01-01 19:28:34
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public ResponseResult login(User user) {
        String username = user.getUsername();
        String password = user.getPassword();

        //没有用户名和密码不能登录
        if (!StringUtils.hasLength(username)){
            return ResponseResult.errorResult(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        if (!StringUtils.hasText(password)){
            return ResponseResult.errorResult(AppHttpCodeEnum.REQUIRE_PASSWORD);
        }

        //根据用户名查找用户
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername,username);
        user = this.getOne(userLambdaQueryWrapper);

        //用户不存在
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR);
        }

        //密码错误
        if (!password.equals(user.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR);
        }

        String token = JwtHelper.createToken(user.getId(), user.getUsername());

        HashMap<Object, Object> map = new HashMap<>();
        map.put("token",token);

        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult info(String token) {
        String userId = JwtHelper.getUserId(token);
        String username = JwtHelper.getUsername(token);
        User user = new User();
        user.setId(userId);
        user.setUsername(username);
        return ResponseResult.okResult(user);
    }

    @Override
    public ResponseResult logout() {
        return ResponseResult.okResult("退出登录");
    }
}

